

from rest_framework import serializers
from django.contrib.auth.models import Group
from users.models import User

# 新建管理员可选分组
class AdminUserGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'name'
        ]

# 管理员用户序列化器
class AdminUserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'email',
            'mobile',

            'groups',
            'user_permissions',

            'password'
        ]

        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, attrs):
        # 重写validate校验函数，对密码加密，以及添加默认is_staff=True有效数据
        # 可以同时作用于后续的新建和更新流程
        attrs['is_staff'] = True
        raw_password = attrs.get('password') # 明文密码

        # make_password是一个全局函数，django利用该函数加密用户密码
        from django.contrib.auth.hashers import make_password
        # 加密
        secret_password = make_password(raw_password) # 密文
        attrs['password'] = secret_password # 把有效数据中的明文覆盖为密文

        return attrs



